/**
 * Created by kedong on 2017/3/1.
 */
(function($){
	$.include(getJsUrlPath(),['lib/plupload-2.1.2/js/plupload.full.min.js', 'spark-md5.js', 'pluploadCommon.js','plupload.css']);
	$.fn.uploader = function(options){
	var that = this;
	var signatureUrl = options.url;
	$.post(signatureUrl, function(data) {
		options.url = data.host;
		options.multipart_params ={
				'policy': data.policy,
				'OSSAccessKeyId': data.accessid,
				'success_action_status': '200', //让服务端返回200,不然，默认会返回204
				'signature': data.signature
		}

		 var defaults = {
			container: '.container',
			ossfile: '.ossfile',
			browse_button: '.selectfiles',
			runtimes: 'html5,flash,silverlight,html4',
			flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
			silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
			prevent_duplicates: true, //不允许队列中存在重复文件
			multi_selection: false,	//不支持多选
			filters: [],
			fileUploadedAfter:function(obj,file){},//文件上传成功之后处理回调方法
			init: {
				PostInit: function () {
					if( this.settings.ossfile){
						var ossFile = uploader.settings.ossfile;               
						ossFile.innerHTML = '';
					}
				},
	
				FilesAdded: function (up, files) {
					var that = this;
					if (up.files.length == 1) {
						var file = files[0];
						//获取文件的md5
						fileMd5(file.getNative(), function (hash) {
							var key = getPath(hash, file.name, that.settings.dir);
							that.settings.multipart_params.key = key;
							var html = '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
								+ '<div class="progress"><div class="progress-bar" style="width: 0"></div></div>'
								+ '</div>';
							$(that.settings.ossfile).html(html);
							
							that.start();
						});
					} else {
						showDangerUI("只能上传一个文件！~~~~~");
						that.each(files, function (file) {
							up.removeFile(file);
						});
					}
				},
	
				UploadProgress: function (up, file) {
					var d = document.getElementById(file.id);
					if(d){
						d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
	
						var prog = d.getElementsByTagName('div')[0];
						var progBar = prog.getElementsByTagName('div')[0];
						progBar.style.width = file.percent + '%';
						progBar.setAttribute('aria-valuenow', file.percent);
					}
				},
	
				FileUploaded: function (up, file, info) {
					if (info.status >= 200 || info.status < 200) {
						// 网络地址
						var filePath = this.settings.url + "/" + this.settings.multipart_params.key;
						file.ossPath=filePath;
						this.showPath.val(filePath);
						this.settings.fileUploadedAfter(this.showPath,file);
						up.removeFile(file);
					}
				},
	
				Error: function (up, err) {
					switch (err.code) {
						case plupload.FILE_EXTENSION_ERROR:
							showDangerUI("上传文件的格式错误,建议上传的格式：" + up.getOption().filters.mime_types[0].extensions);
							break;
						case plupload.FILE_SIZE_ERROR:
							showDangerUI("建议上传文件大小不要超过" + up.getOption().filters.max_file_size);
							break;
						case plupload.IMAGE_DIMENSIONS_ERROR:
							var msg = "";
							if(err.width && err.height){
								msg = "建议上传图片尺寸为"+err.width+"*"+err.height;
							}else if(err.width){
								msg = "图片宽度为"+err.width+",高度不限";
							}else if(err.height){
								msg = "图片高度为"+err.width+",宽度不限";
							}
							showDangerUI("当前图片尺寸为:" + err.imgwidth+"*"+err.imgheight+"," + msg);
							break;
						case plupload.FILE_DUPLICATE_ERROR:
							showDangerUI("文件重复");
							break;
						default:
							console.log(err);
							break;
					}
				},
				
				otheraaa: function(){
					
				}
			}
		}
		 $.extend(defaults, options);
		 
		plupload.addFileFilter("mime_types", function (e, t, n) {
			var that = this
			if(e.length && !e.regexp.test(t.name)){
				that.trigger("Error", {
					code : plupload.FILE_EXTENSION_ERROR,
					message : o.translate("File extension error."),
					file : t
				})
				
				 n(!1)
			}else{
				var typeArray = t.type.split('/');
				if(typeArray[0] == "image"){
						//图片尺寸规格判断限制
						var reader = new FileReader();
						reader.readAsDataURL(t.getNative());
						reader.onload = (function (obj) {
							var image = new Image();
							image.src = obj.target.result;
							image.onload = function () {
									//检测图片的分辨率
									var flag = true;
									if(e[0].width && e[0].width != this.width){
										flag = false;
									}
									
									if(e[0].height && e[0].height != this.height){
										flag = false;
									}
									if (flag) {
											n(!0)
									} else {
										that.trigger("Error", {
											code : plupload.IMAGE_DIMENSIONS_ERROR,
											width:e[0].width,
											height:e[0].height,
											imgwidth:this.width,
											imgheight:this.height,
											file : t
										})
									 n(!1)
								  }
							};
						});
				  }else{
				   n(!0)
				  }
			}
		})
		
		
		//删除图片
		$(".uploader-list").on("click","i",function(){
		   $(this).parent().remove();
		   uploadImg = document.getElementsByName('pic');
		   if(uploadImg.length<8){
			 $('.kf_upload').find('a').show();
		   }
		   uploader.refresh();
		})
		return that.each(function () {
			var that = $(this);
			var	filter = JSON.parse(that.attr("filter") || "{}");
			
			var div = $('<div style="display:inline-block"></div>');
			var container = $('<div class="over_hidden container"></div>');
			var ossfile = $('<div class="ossfile"></div>');
			var browse_button = $('<input type="button" class="selectfiles" value="浏览" />');
			container.append(ossfile);
			div.append(container);
			that.after(div);
			that.after(browse_button);
			defaults.container=container.get(0);
			defaults.ossfile=ossfile.get(0);
			defaults.browse_button=browse_button.get(0);
			if(filter){
				defaults.filters=[filter];
			}
			defaults.multipart_params = {
		            'policy': defaults.policy,
		            'OSSAccessKeyId': defaults.OSSAccessKeyId,
		            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
		            'signature': defaults.signature
		        };
			
			uploader = new plupload.Uploader(defaults);
			uploader.showPath = that;
			uploader.init();
		 });
		});
	}
})(jQuery)